<?php

namespace Plugins\AdminBasic\Requests;

use App\Exception\ApiMessageException;
use App\Requests\AbstractRequest;
use Hyperf\Validation\Rule;
use Plugins\AdminBasic\Enums\BasicSuperConfigEnumType;


/**
 * 超级配置验证器
 */
class BasicSuperConfigRequest extends AbstractRequest
{


    public function allRules(): array
    {
        $needKey = [
            BasicSuperConfigEnumType::SingleItemGroup->value,
            BasicSuperConfigEnumType::AdvancedArray->value,
        ];

        return [
            'id'                     => ["required"],
            'sign'                   => ["required", Rule::unique('basic_super_config', 'sign')->whereNull('delete_time')->ignore($this->input('id'), 'id'), 'regex:/^[a-zA-Z]\w*/'],
            'name'                   => ["required"],
            'type'                   => ["required", Rule::in(BasicSuperConfigEnumType::values())],
            'config_info'            => [Rule::requiredIf(in_array($this->post('type'), $needKey)), "array",],
            'config_info.*.field'    => [Rule::requiredIf(in_array($this->post('type'), $needKey)), "distinct:ignore_case", function($attr, $value) use ($needKey){
                if (in_array($this->post('type'), $needKey)){
                    if (!preg_match('/^[a-zA-Z]/', $value)){
                        throw new ApiMessageException("配置选项的key值必须以字母开头");
                    }
                }
            }],
            'config_info.*.formType' => [Rule::requiredIf(in_array($this->post('type'), $needKey))],
            'config_value'           => ["required", "array"]
        ];
    }

    public function attributes(): array
    {
        return [
            'id'                     => 'ID',
            'sign'                   => '配置的签名',
            'name'                   => '配置的名称',
            'type'                   => '配置的类型',
            'config_info'            => '配置详情',
            'config_value'           => '配置值',
            'config_info.*.field'    => '配置选项Key',
            'config_info.*.formType' => '配置选项表单类型',
            'config_value.*.value'   => '配置选项值',
            'config_value.*.label'   => '配置选项名称',
        ];
    }

    public function updateScene(): array
    {
        return ["id", "sign", "name", "type", "config_info", 'config_info.*.field', 'config_info.*.formType'];
    }

    public function storeScene(): array
    {
        return ["sign", "name", "type", "config_info", 'config_info.*.field', 'config_info.*.formType'];
    }

    public function destroyScene(): array
    {
        return [
            'data' => 'array'
        ];
    }
}